package com.yc.thread;

import java.text.SimpleDateFormat;
import java.util.Date;

public class Test3_Runnable {
    public static void main(String[] args) {
        //创建一个线程 绑定任务
        Runnable task = new ShowTimeTask();
        Thread t = new Thread(task);
        t.start();

        Runnable task2 = new InnerShowTimeTask();
        Thread t2 = new Thread(task2);
        t2.start();

        //匿名内部类写法：
        Thread t3 = new Thread(new Runnable() {
            private boolean flag;

            public void run() {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 hh:mm:ss");
                Date d = null;
                while (!flag) {
                    d = new Date();
                    System.out.println(Thread.currentThread().getName() + "输出当前时间" + sdf.format(d));
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        t3.start();

        //语法四 lambda写法：因为Runnable接口上有@FunctionlInterface 表示这个接口是支持lambda语法
        Thread t4 = new Thread( ()-> {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 hh:mm:ss");
            Date d = null;
            while (true) {
                d = new Date();
                System.out.println(Thread.currentThread().getName() + "输出当前时间" + sdf.format(d));
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        t4.start();
    }

    //第三种：内部类
    static class InnerShowTimeTask implements Runnable {
        private boolean flag = false;

        @Override
        public void run() {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 hh:mm:ss");
            Date d = null;
            while (!flag) {
                d = new Date();
                System.out.println(Thread.currentThread().getName() + "输出当前时间" + sdf.format(d));
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

//外部类从任务角度来看 这是一个任务类=> 将任务与线程绑定
class ShowTimeTask implements Runnable{
    private  boolean flag;
    @Override
    public void run() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 hh:mm:ss");
        Date d= null;
        while (!flag){
            d=new Date();
            System.out.println(Thread.currentThread().getName()+"输出当前时间"+sdf.format(d));
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
